<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-15 10:51:43
 * @LastEditTime: 2024-01-23 09:52:50
-->
<script lang="ts" setup name="ManageApplication">
import useUserStore from '@g/store/modules/user'
import { ikStore } from 'iking-utils'
import { useRouter } from 'vue-router'
import { api } from '@/MainApp/apis/application'

const router = useRouter()
const userStore = useUserStore()

const { t } = useConfig()

const { msgError, msgSuccess, msgBoxWarnAsync } = useMessage()

const state = reactive<any>({
  searchData: {},
  tableData: [],
  fields: [
    {
      // 图标、名称、类型
      key: 'name',
      value: '',
      label: '应用名称',
      width: 170,
      tableSlot: 'name',
      search: true,
      show: true
    },
    {
      key: 'remark',
      value: '',
      label: '应用说明',
      search: true,
      show: true
    }
  ],
  total: 0

})

const methods = {
  initFields: () => {
    if (userStore.categoryCodes.includes('PLATFORM_ADMINISTRATOR')) {
      state.fields.push({
        key: 'status',
        tableSlot: 'status',
        value: '',
        label: '发布状态',
        width: 100,
        search: false,
        show: false
      })
    }
    else if (userStore.categoryCodes.includes('TENANT_ADMINISTRATOR')) {
      state.fields.push({
        key: 'enabled',
        tableSlot: 'enabled',
        value: '',
        label: '启用状态',
        width: 100,
        search: false,
        show: true
      })
    }
    state.fields.push({
      key: '',
      label: '操作',
      show: true,
      width: 120,
      tableSlot: 'operate',
      fixed: 'right',
      showOverflowTooltip: false
    })
  },
  search: async () => {
    const params = {
      ...state.searchData,
      tenantCode: userStore?.tenant?.code || ikStore.local.getItem(ELocal.TENANT)?.code
    }
    const res = await api.select(params)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    state.tableData = res.data
    state.total = res.total
  },
  disable: async (row: any) => {
    const res = await api.disable(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    methods.search()
  },
  enable: async (row: any) => {
    const res = await api.enable(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    methods.search()
  },
  remove: async (row: any) => {
    msgBoxWarnAsync('确认删除', '确定删除吗？', async () => {
      const { success, msg } = await api.remove(row.id)
      if (success) {
        msgSuccess(msg)
        methods.search()
      }
      else {
        msgError(msg)
      }
    })
  }
}

/** 编辑对话框  begin */
const editState = reactive({
  visible: false,
  tableData: [],

  title: '获取应用',
  currentPage: 1,
  pageSize: 5,
  total: 0
})

const editMethods = {
  toApplicationDevelop: async () => {
    const url = `?domain=DEV_CENTER${router.resolve({ path: '/application/develop' }).href}`
    window.open(url)
  },
  add: () => {
    editMethods.search()
    editState.visible = true
  },
  search: async () => {
    const params = {
      page: editState.currentPage,
      rows: editState.pageSize
    }
    const res = await api.selectWithCurrentTenant(params)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    editState.tableData = res.data
    editState.total = res.total
  },
  used: (row: any) => {
    return row.tenantCodes.includes(ikStore.local.getItem(ELocal.TENANT)?.code)
  },
  handleCurrentChange: () => {
    editMethods.search()
  },
  acquire: async (row: any) => {
    const res = await api.acquire(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    editMethods.search()
    methods.search()
  }
}
/** 编辑对话框 end */

const init = () => {
  methods.initFields()
}

init()
</script>

<template>
  <IkPageMain fixed>
    <IkPageFull
      v-model="state.searchData"
      header-title="应用列表"
      :fields="state.fields"
      :table-data="state.tableData"
      :search="methods.search"
      :total="state.total"
    >
      <template #headerRight>
        <!-- v-role="'CREATE-APPLICATION'" -->
        <el-button v-role="'APPLICATION-DEVELOP'" type="primary" @click="editMethods.toApplicationDevelop">应用开发</el-button>
        <el-button v-role="'ACQUIRE-APPLICATION'" type="primary" @click="editMethods.add">获取应用</el-button>
      </template>
      <template #name="{ data }">
        <IkSideText
          :avatar="data.row.icon"
          avatar-type="linearIcon"
          :icon-background-color="data.row.iconBackground"
          :name="data.row.name"
          :text="data.row.name"
          :sub-text="data.row.typeName"
        />
      </template>
      <template #enabled="{ data }">
        <el-popconfirm v-if="data.row.enabled" title="确定停用吗？" @confirm="methods.disable(data.row)">
          <template #reference>
            <span v-role="'DISABLE-APPLICATION'">
              <el-switch :model-value="data.row.enabled" />
            </span>
          </template>
        </el-popconfirm>
        <el-popconfirm v-else title="确定启用吗？" @confirm="methods.enable(data.row)">
          <template #reference>
            <span v-role="'ENABLE-APPLICATION'">
              <el-switch :model-value="data.row.enabled" />
            </span>
          </template>
        </el-popconfirm>
      </template>
      <template #status="{ data }">
        <IkStatu
          :type="data.row.status === 'PUBLISHED' ? 'success' : 'warning'"
          :title="data.row.statusName"
          :circle="true"
        />
      </template>
      <template #operate="{ data }">
        <IkBtnContent :num="2">
          <span v-role="'REMOVE-APPLICATION'">
            <IkTooltip :content="t('移除')">
              <IkSvgIcon
                name="iksvg_shanchu1"
                show-bg
                type="warning"
                @click="methods.remove(data.row)"
              />
            </IkTooltip>
          </span>
        </IkBtnContent>
      </template>
    </IkPageFull>
  </IkPageMain>

  <el-dialog v-model="editState.visible" :title="editState.title">
    <el-table :data="editState.tableData">
      <el-table-column label="应用名称" prop="name">
        <template #default="{ row }">
          <IkSideText
            :avatar="row.icon"
            avatar-type="linearIcon"
            :icon-background-color="row.iconBackground"
            :text="row.name"
            :sub-text="row.typeName"
          />
        </template>
      </el-table-column>
      <el-table-column label="应用说明" prop="remark" />
      <el-table-column width="100px" label="操作">
        <template #default="{ row }">
          <span v-if="row.assignToCurrentTenant" type="primary">已分配</span>
          <el-button
            v-else
            link
            type="primary"
            @click="editMethods.acquire(row)"
          >
            获取
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model="editState.currentPage"
      style="margin-top: 8px"
      :total="editState.total"
      :page-size="editState.pageSize"
      layout="slot, ->, prev, pager, next,  jumper"
      @current-change="editMethods.handleCurrentChange"
    >
      <template #default>
        <span class="total">
          共<span class="num">{{ editState.total }}</span>
          项数据
        </span>
      </template>
    </el-pagination>
  </el-dialog>
</template>
